<template>
    <div class="wrap">
        <span class="title" v-if="title">{{title}}</span>
        <el-tag class="tag" :disable-transitions="true" v-for="(tag, index) in list" :key="index" size="medium" closable @close="del(index)">{{tag}}</el-tag>
        <el-input v-if="list.length < maxlength" size="mini" class="input" v-model="value" placeholder="回车添加" @keypress.native="keypress" @keydown.native="keydown"></el-input>
        <el-button v-if="list.length < maxlength" @click="add" class="button" size="mini">添加</el-button>
    </div>    
</template>
<script>
export default {
    name:"input-tags",
    props:['tags','title','maxlength'],
    data(){
        return {
            value:'',
            list:['aaaa','bbbb']
        }
    },
    mounted(){
        this.list = this.tags
    },
    watch:{
        tags(val,oldVal){
            console.log(val)
            this.list = this.tags
        }
    },
    methods:{
        del(index){
            this.list.splice(index,1)
            this.change()
        },
        add(){
            if(this.value.trim()!=''){
                this.list.push(this.value)
                this.value = '' 
                this.change() 
            }        
        },
        keypress(e){
            if(e.keyCode ===13){
                this.add()    
            }  
        },
        keydown(e){
            if(e.keyCode===8 && this.value===''){
                const last = this.list.length-1
                this.del(last) 
                this.change()  
            }
        },

        change(){
            this.$emit('change',this.list)
        }
    }
}
</script>
<style scoped>
    .title{
        margin-top: 5px;  
        margin-right: 5px; 
    }
    .input{
        width: auto;
        margin-top: 5px;
    }
    .button{
       margin-top: 5px; 
    }
    .input >>> .el-input__inner{
        width: 100px!important;
    }
    .tag{
        margin-top: 5px;
        margin-right: 5px;
        height: auto;
        word-break: break-all;
        white-space: inherit;
    }
</style>